package org.monster.context.core;

import org.monster.context.core.filter.ApplicationFilterConfig;
import org.monster.context.reader.tag.FilterTag;

import javax.servlet.Filter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 过滤器初始化模式
 */
public class FilterInitPattern implements FilterPattern {

    /**
     * 日志器
     */
    private static final Logger logger = Logger.getLogger(FilterInitPattern.class.getName());
    /**
     * 过滤器配置键值
     */
    private static final FilterConfigCache FILTER_CONFIG_CACHE = FilterConfigCache.getFilterConfigCache();

    /**
     * 装载 过滤器
     *
     * @param key       键
     * @param clazz     类
     * @param filterTag 拦截器标签
     * @throws IllegalAccessException 非法访问异常
     * @throws IllegalArgumentException 非法参数异常
     */
    @Override
    public void loadFilter(String key, Class<?> clazz, FilterTag filterTag)
            throws IllegalAccessException, IllegalArgumentException {
        Method init;
        try {
            init = clazz.getDeclaredMethod("init",
                    javax.servlet.FilterConfig.class);
            Filter filter = (Filter) clazz.newInstance();
            if (init != null) {
                init.invoke(filter, new ApplicationFilterConfig());
            }
            FILTER_CONFIG_CACHE.addFilter(key + "_" + filterTag.getFilterClass(),
                    filter);
        } catch (NoSuchMethodException | SecurityException
                | InstantiationException | InvocationTargetException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
}
